<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use onekey\File;
use think\facade\Db;
use think\facade\View;
use app\admin\BaseController;
use app\admin\model\AdminMenu;
use app\admin\model\Curd as CurdModel;
/**
 * 一键生成代码
 */
class Curd extends BaseController
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $input = input('post.');
            $data  = CurdModel::withSearch(['keyword'], $input)->order('sort', 'desc')->select();
            $publicMenu = [];
            foreach ($this->request->menu as $key => $value) {
                if ($value['ifshow'] === 1) {
                    array_push($publicMenu, $value);
                }
            }
            return json(['status' => 'success', 'message' => '获取成功', 'data' => $data, 'publicMenu' => $publicMenu]);
        } else {
            $table  = array_column(Db::query('SHOW TABLES'),'Tables_in_'.env('database.database'));
            $result = api_post('tokenSystem/table', ['table' => $table]);
            if ($result['status'] === 'success') {
                foreach ($result['data'] as $val) {
                    $exist = CurdModel::where('name', $val)->find();
                    $props = Db::query("SHOW FULL COLUMNS FROM $val");
                    // 存在表则对比字段
                    if ($exist) {
                        $field = $exist->field;
                        foreach ($props as $key => $prop) {
                            if (! in_array($prop['Field'], array_column($field, 'prop'))) {
                                $label = empty($prop['Comment']) ? $prop['Field'] : $prop['Comment'];
                                $array = [
                                    'is'          => 'el-input',
                                    'key'         => $prop['Key'],
                                    'prop'        => $prop['Field'],
                                    'label'       => $label,
                                    'colMd'       => '',
                                    'default'     => '',
                                    'placeholder' => '',
                                    'filterable'  => true,
                                    'multiple'    => true,
                                    'type'        => '',
                                    'child'       => [],
                                    'tips'        => '',
                                    'required'    => false,
                                    'pattern'     => '',
                                    'disabled'    => false,
                                    'formShow'    => true,
                                    'tableWidth'  => 0,
                                    'tableBind'   => [],
                                    'tableSort'   => true,
                                    'tableProp'   => $prop['Field'],
                                    'tableLabel'  => $label,
                                    'tableShow'   => true,
                                ];
                                array_push($field, $array);
                            }
                        }
                        $exist->field = $field;
                        $exist->save();
                    } else {
                        $field = [];
                        foreach ($props as $key => $prop) {
                            $field[$key]['is']          = 'el-input';
                            $field[$key]['key']         = $prop['Key'];
                            $field[$key]['prop']        = $prop['Field'];
                            if ($prop['Key'] === 'PRI') {
                                 $field[$key]['label']  = '编号';
                            } else {
                                $field[$key]['label']   = empty($prop['Comment']) ? $prop['Field'] : $prop['Comment'];
                            }
                            $field[$key]['colMd']       = '';
                            $field[$key]['default']     = '';
                            $field[$key]['placeholder'] = '';
                            $field[$key]['filterable']  = true;
                            $field[$key]['multiple']    = true;
                            $field[$key]['type']        = '';
                            $field[$key]['child']       = [];
                            $field[$key]['tips']        = '';
                            $field[$key]['required']    = false;
                            $field[$key]['pattern']     = '';
                            $field[$key]['disabled']    = false;
                            $field[$key]['formShow']    = $prop['Key'] === 'PRI' ? false : true;
                            $field[$key]['tableWidth']  = 0;
                            $field[$key]['tableBind']   = [];
                            $field[$key]['tableSort']   = true;
                            $field[$key]['tableProp']   = $field[$key]['prop'];
                            $field[$key]['tableLabel']  = $field[$key]['label'];
                            $field[$key]['tableShow']   = true;
                        }
                        CurdModel::create([
                            'cover'                 => '',
                            'title'                 => '未命名',
                            'name'                  => $val,
                            'field'                 => $field,
                            'sort'                  => 0,
                            'plugin'                => '',
                            'number'                => 0,
                            'form_label_width'      => 100,
                            'form_col_md'           => 24,
                            'table_tree'            => 0,
                            'table_expand'          => 0,
                            'table_export'          => 1,
                            'table_sort'            => '',
                            'table_page_size'       => 20,
                            'table_operation_width' => 0,
                            'search_catalog'        => [],
                            'search_status'         => [],
                            'search_keyword'        => 1,
                            'search_date'           => 1,
                            'preview'               => 0,
                            'create_time'           => date('Y-m-d H:i:s')
                        ]);
                    }
                }
            }
            return View::fetch();
        }
    }

    /**
     * 保存更新的资源
     */
    public function update()
    {
        if ($this->request->isPost()) {
            CurdModel::update(input('post.'));
            return json(['status' => 'success', 'message' => '修改成功']);
        }
    }
    
    /**
     * 生成代码
     */
    public function code()
    {
        if ($this->request->isPost()) {
            $input = input('post.');
            // 插件目录
            $pluginPath = plugin_path() . $input['name'] . '/';
            File::dirMkdir($pluginPath);
            // 基础信息
            $pluginInfo = [
                'title'  => $input['title'],
                'name'   => $input['name'],
                'status' => 1,
                'sort'   => 0,
            ];
            File::create($pluginPath.'info.php', "<?php\nreturn ".var_export($pluginInfo,true).";");
            // 生成后台控制器、模型、视图、API、路由、菜单权限
            AdminMenu::where('type', $input['name'])->delete();
            foreach ($input['table'] as $key => $value) {
                $name     = $value['name'];
                $viewPath = str_replace('mk_','', $name);
                $path     = ucwords(str_replace('_', ' ', $viewPath));
                $path     = str_replace(' ','',lcfirst($path));
                $class    = ucfirst($path);
                $field    = $value['field'];
                include(app_path() . "addons/Curd.php");
                // 后台
                File::create($pluginPath . "admin/view/$viewPath/index.html", $adminView);
                File::create($pluginPath . "admin/model/$class.php", $admminModel);
                File::create($pluginPath . "admin/controller/$class.php", $adminController);
                // API
                File::create($pluginPath . "api/controller/$class.php", $apiController);
                File::create($pluginPath . "api/validate/$class.php", $apiValidate);
                File::create($pluginPath . "api/model/$class.php", $apiModel);
                // 路由
                $routes[]   = ["catalog" => $viewPath, "title" => $value['title'], "table" => $viewPath];
                // 菜单
                $menuParent = AdminMenu::create([
                    'pid'        => 0,
                    'title'      => $value['title'],
                    'icon'       => $value['cover'],
                    'path'       => $input['name'] . '/' .$path . '/index',
                    'sort'       => 0,
                    'ifshow'     => 1,
                    'logwriting' => 0,
                    'type'       => $input['name'],
                ]);
                AdminMenu::create([
                    'pid'        => $menuParent['id'],
                    'title'      => '查看',
                    'icon'       => '',
                    'path'       => $input['name'] . '/' .$path . '/index',
                    'sort'       => 0,
                    'ifshow'     => 0,
                    'logwriting' => 0,
                    'type'       => $input['name'],
                ]);
                AdminMenu::create([
                    'pid'        => $menuParent['id'],
                    'title'      => '编辑',
                    'icon'       => '',
                    'path'       => $input['name'] . '/' .$path . '/update',
                    'sort'       => 0,
                    'ifshow'     => 0,
                    'logwriting' => 1,
                    'type'       => $input['name'],
                ]);
                AdminMenu::create([
                    'pid'        => $menuParent['id'],
                    'title'      => '添加',
                    'icon'       => '',
                    'path'       => $input['name'] . '/' .$path . '/save',
                    'sort'       => 0,
                    'ifshow'     => 0,
                    'logwriting' => 1,
                    'type'       => $input['name'],
                ]);
                AdminMenu::create([
                    'pid'        => $menuParent['id'],
                    'title'      => '删除',
                    'icon'       => '',
                    'path'       => $input['name'] . '/' .$path . '/delete',
                    'sort'       => 0,
                    'ifshow'     => 0,
                    'logwriting' => 1,
                    'type'       => $input['name'],
                ]);
                // 次数
                CurdModel::where('name', $value['name'])->update([
                    'number' => $value['number'] + 1,
                    'plugin' => $input['name'],
                ]);
            }
            File::create($pluginPath.'route.php', "<?php\nreturn ".var_export($routes,true).";");
            return json(['status' => 'success','message' => '一键生成插件成功']);
        }
    }
    
    /**
     * 删除指定资源
     */
    public function delete()
    {
        if ($this->request->isPost()) {
            CurdModel::destroy(input('post.ids'));
            return json(['status' => 'success', 'message' => '删除成功']);
        }
    }
}
